<template>
  <div class="md-amap-base">
    <div class="md-amap-search" v-if="isSearch">
      <el-input v-model="word" placeholder="请输入地名" size="small" style="width: 200px;" />
      <el-button type="primary" size="small" style="margin-left: 10px;" @click="handleLoadAMap()">搜索</el-button>
    </div>

    <div id="mdAMapContainer" :style="{width:width, height:height}"></div>
  </div>
</template>

<script>
import { mdAmapKey, mdAmapVersion } from '@/ddd/config.service.js'
import AMapLoader from '@amap/amap-jsapi-loader'
export default {
  name: 'MdAMapBaseComponent',
  props: {
    /**
     * 初始化地图中心点位置
     * lng,lat
     */
    value: {
      type: Array,
      default: () => [116.397428, 39.90923]
    },
    /** 是否显示搜索 */
    isSearch: {
      type: Boolean,
      default: true
    },
    /**
     * 输入提示时限定城市。
     * 可选值：城市名（中文或中文全拼）、citycode、adcode；
     * 默认值：“全国”
     */
    city: {
      type: Array,
      default: () => ['全国']
    },
    /** 
     * 是否点击选择当前位置坐标
      */
    isSelectCurrentLngLat: {
      type: Boolean,
      default: false
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '200px'
    }
  },
  data () {
    return {
      amap: null,
      center: [116.397428, 39.90923],
      word: ''
    }
  },
  watch: {
    value: {
      handler (val) {
        if (val.length > 0) {
          this.center = val
        }
      },
      deep: true,
      immediate: true
    },
    city: {
      handler (val) {
        if (val.length > 2) {
          this.word = val[val.length - 1]
        }
        this.handleLoadAMap()
      },
      deep: true,
      immediate: true
    }
  },
  mounted () {
    this.handleLoadAMap()
  },
  methods: {
    /** 加载地图 */
    async handleLoadAMap () {
      try {
        const AMap = await AMapLoader.load({ key: mdAmapKey, version: mdAmapVersion, plugins: ['AMap.AutoComplete'] })

        const searchRes = new AMap.AutoComplete({
          city: this.city[0]
        })

        if (!this.word) {
          this.amap = new AMap.Map('mdAMapContainer', {  //设置地图容器id
            resizeEnable: true,
            zoom: 13,           //初始化地图级别
            center: this.center
          })

          const initMarker = new AMap.Marker({
            map: this.amap,
            icon: require('@/assets/img/icon-map-location.png'),
            position: new AMap.LngLat(this.center[0], this.center[1]),
            offset: new AMap.Pixel(-13, -30)
          })

          this.amap.add(initMarker)

          if (!this.isSelectCurrentLngLat) {
            return
          }

          this.amap.on('click', async (event) => {
            this.amap.clearMap()

            const marker = new AMap.Marker({
              map: this.amap,
              icon: require('@/assets/img/icon-map-location.png'),
              position: new AMap.LngLat(event.lnglat.lng, event.lnglat.lat),
              offset: new AMap.Pixel(-13, -30)
            })

            this.amap.add(marker)

            this.$emit('input', [event.lnglat.lng, event.lnglat.lat])
          })
        } else {
          searchRes.search(this.word, (status, result) => {
            if (status !== 'complete') {
              this.$message.warning('地图异常,请联系管理员')
              return
            }

            if (result && result.info === 'OK' && result.tips && result.tips.length > 0) {
              const tip = result.tips.find(e => e.location && e.location.lng && e.location.lat)
              if (tip) {
                this.center = [tip.location.lng, tip.location.lat]

                this.$emit('input', this.center)

                this.amap = new AMap.Map('mdAMapContainer', {  //设置地图容器id
                  resizeEnable: true,
                  zoom: 13,           //初始化地图级别
                  center: this.center
                })

                const initMarker = new AMap.Marker({
                  map: this.amap,
                  icon: require('@/assets/img/icon-map-location.png'),
                  position: new AMap.LngLat(this.center[0], this.center[1]),
                  offset: new AMap.Pixel(-13, -30)
                })

                this.amap.add(initMarker)

                if (!this.isSelectCurrentLngLat) {
                  return
                }

                this.amap.on('click', async (event) => {
                  this.amap.clearMap()

                  const marker = new AMap.Marker({
                    map: this.amap,
                    icon: require('@/assets/img/icon-map-location.png'),
                    position: new AMap.LngLat(event.lnglat.lng, event.lnglat.lat),
                    offset: new AMap.Pixel(-13, -30)
                  })

                  this.amap.add(marker)

                  this.$emit('input', [event.lnglat.lng, event.lnglat.lat])
                })
              } else {
                this.$message.warning('未搜索出结果')
              }
            } else {
              this.$message.warning('未搜索出结果')
            }
          })
        }
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.md-amap-base {
  .md-amap-search {
    margin-bottom: 20px;
  }
}
</style>